﻿using System;
using System.IO;

namespace YYFUtils
{
    /// <summary>
    /// 写文件
    /// </summary>
    public static class WriteHelper
    {

        #region 写文件
        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="content"></param>
        /// <param name="filename"></param>
        /// <param name="ex"></param>
        public static void WriteLog(string content, string filename = "", bool console = true, bool hastime = true, string directory = "log", string ext = "log", ConsoleColor fontColor = ConsoleColor.Gray, bool hasdef = true, Exception ex = null, string rootdir = null)
        {
            if (fontColor != ConsoleColor.Gray)
            {
                Console.ForegroundColor = fontColor;
            }
            if (hastime)
            {
                content = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "：" + content;
            }
            if (console)
            {
                Console.WriteLine(content);
            }
            if (string.IsNullOrWhiteSpace(directory)) directory = "log";
            else
            {
                if (hasdef)
                {
                    directory = directory + "_log";
                }
            }
            if (string.IsNullOrWhiteSpace(ext)) ext = "log";
            string dir = AppDomain.CurrentDomain.BaseDirectory + directory;
            if (!string.IsNullOrWhiteSpace(rootdir))
            {
                if (!rootdir.EndsWith("/"))
                {
                    rootdir = rootdir + "/";
                }
                dir = rootdir + directory;
            }
            if (!System.IO.Directory.Exists(dir))
            {
                System.IO.Directory.CreateDirectory(dir);
            }
            if (ex != null)
            {
                if (string.IsNullOrWhiteSpace(filename))
                {
                    filename = "err";
                }
                content += System.Environment.NewLine + ex.StackTrace;
            }
            string file = dir + "//" + filename + "." + ext;
            if (hasdef)
            {
                if (!string.IsNullOrWhiteSpace(filename)) { filename = filename + "_"; }
                file = dir + "//" + filename + DateTime.Now.ToString("yyyyMMdd") + "." + ext;
            }
            else if (string.IsNullOrWhiteSpace(filename))
            {
                file = dir + "//log." + ext;
            }
            if (File.Exists(file))
            {
                writeLogToFile(file, content);
            }
            else
            {
                createAndWriteLogFile(file, content);
            }
            if (fontColor != ConsoleColor.Gray)
            {
                Console.ForegroundColor = ConsoleColor.Gray;
            }
        }
        public static void WriteText(string content, out string outfilepath, string filename = "")
        {
            string dir = AppDomain.CurrentDomain.BaseDirectory + "log";
            if (!System.IO.Directory.Exists(dir))
            {
                System.IO.Directory.CreateDirectory(dir);
            }
            outfilepath = dir + "//" + filename + DateTime.Now.Ticks.ToString() + ".txt";
            if (File.Exists(outfilepath))
            {
                writeLogToFile(outfilepath, content);
            }
            else
            {
                createAndWriteLogFile(outfilepath, content);
            }
        }

        /// <summary>
        /// 写入文件
        /// </summary>
        /// <param name="content">文件内容</param>
        /// <param name="outfilepath">文件路径</param>
        /// <param name="filename">文件名</param>
        /// <param name="ext">扩展名 默认 .txt </param>
        /// <param name="rand">文件名随机后缀</param>
        /// <param name="directory">文件夹</param>
        /// <param name="isadd">是否追加</param>
        public static void WriteFile(string content, out string outfilepath, string filename = "", string ext = ".txt", bool rand = false, string directory = "file", bool isadd = true)
        {
            string dir = AppDomain.CurrentDomain.BaseDirectory + directory;
            if (!System.IO.Directory.Exists(dir))
            {
                System.IO.Directory.CreateDirectory(dir);
            }
            outfilepath = dir + "//" + filename + (rand ? DateTime.Now.ToString("yyyyMMdd") : "") + ext;

            if (File.Exists(outfilepath))
            {
                if (isadd)
                {
                    writeLogToFile(outfilepath, content);
                }
            }
            else
            {
                createAndWriteLogFile(outfilepath, content);
            }
        }

        /// <summary>
        /// 追加写入文件
        /// </summary>
        static private void writeLogToFile(string file, string logInfo)
        {
            try
            {
                using (StreamWriter m_streamWriter = File.AppendText(file))
                {
                    m_streamWriter.Flush();
                    m_streamWriter.WriteLine(logInfo);
                    m_streamWriter.Flush();
                    m_streamWriter.Dispose();
                    m_streamWriter.Close();
                }
            }
            catch { }
        }
        /// <summary>
        /// 创建写入文件
        /// </summary>
        /// <param name="file"></param>
        /// <param name="logInfo"></param>
        static private void createAndWriteLogFile(string file, string logInfo)
        {
            string folder = file.Substring(0, file.LastIndexOf("\\"));
            if (!System.IO.Directory.Exists(folder))
            {
                System.IO.Directory.CreateDirectory(folder);
            }
            try
            {
                FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write);
                using (StreamWriter m_streamWriter = new StreamWriter(fs))
                {
                    m_streamWriter.Flush();
                    m_streamWriter.WriteLine(logInfo);
                    m_streamWriter.Flush();
                    m_streamWriter.Dispose();
                    m_streamWriter.Close();
                }
            }
            catch { }
            finally
            {
                //fs.Dispose();
                //fs.Close();
            }
        }
        #endregion
    }
}
